/*
 *   Copyright 2023 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.asialjim.encommunicate.rsa.server.filter;

import com.asialjim.encommunicate.rsa.filter.ApplicationEnDecryptChecker;
import com.asialjim.encommunicate.rsa.management.key.RSAKeyLookUpComponent;
import com.asialjim.encommunicate.rsa.management.pojo.AppEnDecryptInfo;
import com.asialjim.encommunicate.rsa.server.config.RSAConfigProperty;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;

/**
 * RSA 加解密过滤器配置
 *
 * @author Copyright © <a href="mailto:asialjim@hotmail.com">Asial Jim</a>   Co., LTD
 * @version 1.0
 * @since 2023/2/28, &nbsp;&nbsp; <em>version:1.0</em>, &nbsp;&nbsp; <em>java version:17</em>
 */
@Configuration
public class RSAEncryptFilterConfiguration implements InitializingBean {
    @Autowired private RSAKeyLookUpComponent lookUpComponent;
    @Autowired(required = false) private RSAConfigProperty configProperty;

    @Bean
    @ConditionalOnMissingBean
    public ApplicationEnDecryptChecker applicationEnDecryptChecker() {
        return ApplicationEnDecryptChecker.DEFAULT;
    }

    @Override
    public void afterPropertiesSet() {
        if (Objects.isNull(configProperty))
            return;

        List<AppEnDecryptInfo> apps = configProperty.getApps();
        if (CollectionUtils.isEmpty(apps))
            return;

        apps.forEach(lookUpComponent::modify);
    }
}